<?php
/**
 * MySQL 连接类
 * User: lisgroup
 * Date: 2017/11/3
 * Time: 10:14
 */

namespace Apps\lib;


class MysqlQuery
{
    // 数据库连接
    private $conn;

    // 初始化连接资源

    /**
     * Mysql constructor.
     * @param array $config
     */
    public function __construct($config = array('DB_HOST' => 'localhost', 'DB_PORT' => '3306', 'DB_USER' => 'root', 'DB_PASS' => 'root', 'DB_NAME' => 'test', 'DB_CHARSET' => 'utf8'))
    {
        if (!$this->conn) {
            $this->conn = new \mysqli($config['DB_HOST'], $config['DB_USER'], $config['DB_PASS'], $config['DB_NAME'], $config['DB_PORT']);
            if ($this->conn->connect_errno) {
                printf("Connect failed: %s\n", $this->conn->connect_error);
                exit();
            }
            $this->conn->set_charset($config['DB_CHARSET']);
        }
    }

    // 查询方法
    public function query($sql)
    {
        return $this->conn->query($sql);
    }

    // 1. 获取二维数组多列结果
    public function getAll($sql)
    {
        $result = $this->query($sql);
        $array = array();
        if ($result) {
            while ($row = $result->fetch_assoc()) {
                $array[] = $row;
            }
        }
        return $array;
    }

    // 2. 获取一列数据
    public function getCol($sql)
    {
        $result = $this->query($sql);
        $array = array();

        if ($result) {
            while ($row = $result->fetch_row()) {
                $array[] = $row[0];
            }
        }
        return $array;
    }

    // 3. 获取一行数据
    public function getRow($sql)
    {
        $result = $this->query($sql);
        return $result->fetch_assoc();
    }

    // 4. 获取单个数据
    public function getOne($sql)
    {
        $result = $this->query($sql);
        $row = $result->fetch_row();

        $string = '';
        if ($row) {
            $string = $row[0];
        }

        return $string;
    }

    // 关闭数据库连接
    public function close()
    {
        $this->conn->close();
    }

    // 待添加功能

    public function __destruct()
    {
        $this->close();
    }

}